﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO.Ports;
using System.Threading;

namespace 实验2
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            InitializeComboBox1(ComboBox1);

            InitializeComboBox2(ComboBox2);
        }

        private void InitializeComboBox1(ComboBox combo)
        {
            string[] ports = SerialPort.GetPortNames();

            Array.Sort(ports);

            foreach (string sName in ports)
            {
                combo.Items.Add(sName);
            }
        }

        private void InitializeComboBox2(ComboBox combo)
        {
            string[] baudrate = { "9600", "19200", "38400", "57600" };

            foreach (string number in baudrate)
            {
                combo.Items.Add(number);
            }
        }

        private char[] character = { 'a', 'b', 'c'};

        private SerialPort port = new SerialPort();

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            if (port.IsOpen)
                port.Close();

            try
            {
                port.PortName = ComboBox1.SelectedItem.ToString();

                port.BaudRate = 9600;

                port.Open();

                while (port.ReadExisting() == null) { }

                MessageBox.Show(port.ReadExisting());

                if (int.Parse(ComboBox2.SelectedItem.ToString()) == 19200)
                    port.Write(character, 0, 1);

                else if (int.Parse(ComboBox2.SelectedItem.ToString()) == 38400)
                    port.Write(character, 1, 1);

                else if (int.Parse(ComboBox2.SelectedItem.ToString()) == 57600)
                    port.Write(character, 2, 1);

                port.BaudRate = int.Parse(ComboBox2.SelectedItem.ToString());
            }

            catch
            {
                port = new SerialPort();

                MessageBox.Show("参数未输入完整！");
            }
        }

        private void Button2_Click(object sender, RoutedEventArgs e)
        {

            if (port.IsOpen)
                port.Close();
        }

        private bool flag = true;

        private void RadioButton_Clicked(object sender, RoutedEventArgs e)
        {
            RadioButton1.IsChecked = flag;

            flag = !flag;
        }
    }
}
